﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Charades.Web.DAL.DBMSAdapters.MSSQL;

namespace Charades.Web.DAL
{
	/// <summary>
	/// Root handler for all high-level DB actions.
	/// Responsible for initialization, testing and instantiating of underlying adapters
	/// that performs actual low-level operations over DBMS engine.
	/// </summary>
	public sealed class DBHandler : IDisposable
	{
		private static Type _adapterType;

		private IDBMSAdapter CurrentAdapter
		{
			get
			{
				return (IDBMSAdapter)Activator.CreateInstance(_adapterType);
			}
		}

		public static bool IsInitialized = false;

		public DBHandler()
		{
			if(!IsInitialized) throw new TypeInitializationException(typeof(DBHandler).FullName, new Exception("DBHandler must be initialized before using"));
		}

		/// <summary>
		/// Performs basic initialization and testing of selected adapter
		/// </summary>
		public static void Init<T>()
		{
			// let's test if passed type actually represents an adapter...
			if (typeof(IDBMSAdapter).IsAssignableFrom(typeof(T)))
			{
				_adapterType = typeof(T);

				//...and perform initial test, if so
				var testAdapter = (IDBMSAdapter)Activator.CreateInstance(typeof(T));
				testAdapter.InitAdapter();
				IsInitialized = true;

			}
			else
			{
				throw new Exception("Trying to initialize " + typeof(T).FullName + " as adapter. Existent and implemented adapters allowed only");
			}
		}

		/// <summary>
		/// Fetches list of quiz words from storage
		/// </summary>
		/// <returns>List of fetched words</returns>
		public List<string> GetAllWords()
		{
			return CurrentAdapter.FetchAllWords();
		}


		public void Dispose()
		{

		}
	}
}